<template>
  <div class="report-page">
    <el-card class="toolbar-card">
      <div class="toolbar">
        <div class="title">销售比例报表</div>
        <div class="actions">
          <el-button type="primary" @click="loadData">刷新</el-button>
          <el-button @click="handleExport">导出CSV</el-button>
        </div>
      </div>
    </el-card>

    <el-card class="chart-card">
      <div ref="chartRef" class="chart" />
    </el-card>

    <el-card class="table-card">
      <el-table :data="tableData" v-loading="loading" border>
        <el-table-column type="index" label="#" width="60" />
        <el-table-column v-for="col in columns" :key="col.prop" :prop="col.prop" :label="col.label" show-overflow-tooltip />
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, computed } from 'vue'
import * as echarts from 'echarts'
import { ElMessage } from 'element-plus'
import { reportApi } from '@/api/report/report'

const loading = ref(false)
const tableData = ref([])
const chartRef = ref(null)
let chart

// 列标题映射表 - 只保留需要显示的字段
const columnMapping = {
  name: '名称',
  productName: '产品名称',
  categoryName: '分类名称',
  region: '地区',
  salesAmount: '销售金额',
  salesQuantity: '销售数量',
  percentage: '占比',
  totalAmount: '总金额',
  totalQuantity: '总数量',
  month: '月份',
  year: '年份',
  productCode: '产品编码',
  category: '分类',
  amount: '金额',
  quantity: '数量',
  ratio: '比例',
  value: '数值',
  code: '编码'
}

const columns = computed(() => {
  if (!tableData.value.length) return []
  // 只显示有数据的字段，过滤掉空值字段
  const dataKeys = Object.keys(tableData.value[0]).filter(key => {
    const hasData = tableData.value.some(item => item[key] !== null && item[key] !== undefined && item[key] !== '')
    return hasData && columnMapping[key]
  })
  return dataKeys.map(key => ({
    prop: key,
    label: columnMapping[key] || key
  }))
})

const renderChart = () => {
  if (!chart) { 
    chart = echarts.init(chartRef.value)
    window.addEventListener('resize', () => chart && chart.resize()) 
  }
  if (!tableData.value.length) { 
    chart.clear()
    return 
  }
  
  // 获取数据，确保数据类型正确，避免显示"未知"
  const data = tableData.value.map(i => {
    // 优先使用分类名称，如果没有则使用产品名称
    let name = '未命名分类'
    if (i.categoryName && i.categoryName.trim()) {
      name = i.categoryName
    } else if (i.productName && i.productName.trim()) {
      name = i.productName
    } else if (i.name && i.name.trim()) {
      name = i.name
    }
    
    // 获取数值，优先使用占比，如果没有则使用销售金额
    let value = 0
    if (i.percentage !== null && i.percentage !== undefined && i.percentage !== '') {
      value = i.percentage
    } else if (i.value !== null && i.value !== undefined && i.value !== '') {
      value = i.value
    } else if (i.salesAmount !== null && i.salesAmount !== undefined && i.salesAmount !== '') {
      value = i.salesAmount
    } else if (i.salesQuantity !== null && i.salesQuantity !== undefined && i.salesQuantity !== '') {
      value = i.salesQuantity
    }
    
    // 确保是数字类型
    if (typeof value === 'number') {
      return { name, value }
    }
    if (typeof value === 'string') {
      const parsed = parseFloat(value)
      return { name, value: isNaN(parsed) ? 0 : parsed }
    }
    return { name, value: 0 }
  }).filter(item => item.value > 0) // 过滤掉值为0的数据
  
  console.log('销售比例图表数据:', data) // 添加调试日志
  
  chart.setOption({
    tooltip: { 
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c}% ({d}%)'
    },
    legend: { 
      orient: 'vertical',
      left: 'left',
      top: 10
    },
    series: [{ 
      type: 'pie', 
      name: '销售比例',
      radius: '50%',
      data: data,
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }]
  })
}

const loadData = async () => {
  loading.value = true
  try {
    const res = await reportApi.getSalesRatio()
    console.log('销售比例API响应:', res) // 添加调试日志
    
    let list = []
    if (Array.isArray(res)) {
      list = res
    } else if (res && res.data) {
      list = Array.isArray(res.data) ? res.data : [res.data]
    } else if (res && typeof res === 'object') {
      // 如果返回的是对象，尝试提取数据
      list = Object.values(res).filter(item => Array.isArray(item)).flat()
    }
    
    console.log('处理后的销售比例数据:', list) // 添加调试日志
    tableData.value = list
    
    await nextTick()
    renderChart()
  } catch (e) {
    console.error('获取销售比例失败:', e)
    ElMessage.error('获取销售比例失败')
    tableData.value = []
    renderChart()
  } finally { 
    loading.value = false 
  }
}

const handleExport = () => {
  if (!tableData.value.length) return ElMessage.warning('暂无数据可导出')
  const headers = columns.value.map(col => col.label)
  const rows = tableData.value.map(r => columns.value.map(col => r[col.prop] ?? ''))
  const csv = '\uFEFF' + [headers.join(','), ...rows.map(r => r.join(','))].join('\n')
  const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `销售比例_${new Date().toISOString().slice(0,10)}.csv`
  a.click(); URL.revokeObjectURL(url)
}

onMounted(() => loadData())
</script>

<style scoped>
.report-page { display: grid; gap: 12px; }
.toolbar { display: flex; justify-content: space-between; align-items: center; }
.title { font-weight: 600; }
.chart { width: 100%; height: 420px; }
</style>
